package com.lsu.command.experiment;

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

/**
 * 请求者
 *
 * @Author wang suo
 * @Date 2020/10/21 0021 15:31
 * @Version 1.0
 */
class Invoker extends JPanel {
    private Command command;
    private ConcreteInvoker concreteInvoker;

    Invoker(Command command, ConcreteInvoker concreteInvoker) {
        this.command = command;
        this.concreteInvoker = concreteInvoker;
        this.addMouseListener(new Mouse());
        this.addMouseMotionListener(new MouseMotion());
    }

    private void executeCommand(MouseEvent event) {
        int x = event.getX();
        int y = event.getY();
        Circle circle = new Circle(x, y);
        int button = event.getButton();

        if (button == MouseEvent.BUTTON1) {
            this.command.execute(this, circle);
            concreteInvoker.notifyObservers(1, event.getX(), event.getY());
        } else if (button == MouseEvent.BUTTON3) {
            this.command.undo(this);
        }
    }

    class Mouse implements MouseListener {

        @Override
        public void mouseClicked(MouseEvent e) {
            executeCommand(e);
        }

        @Override
        public void mousePressed(MouseEvent e) {}

        @Override
        public void mouseReleased(MouseEvent e) {}

        @Override
        public void mouseEntered(MouseEvent e) {}

        @Override
        public void mouseExited(MouseEvent e) {}
    }

    class MouseMotion implements MouseMotionListener {

        @Override
        public void mouseDragged(MouseEvent e) {}

        @Override
        public void mouseMoved(MouseEvent e) {
            concreteInvoker.notifyObservers(0, e.getX(), e.getY());
        }
    }
}
